package com.star.spring.deferred.utils;


import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.StringJoiner;
import java.util.concurrent.TimeUnit;

/**
 * @description: 测试多线程的工具类
 * @author: star
 * @create: 2024-12-22 01:03
 **/

public class CommonUtils {

    // 休眠
    public static void sleep(long time) {

        try {
            TimeUnit.SECONDS.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    // 打印日志
    public static void log(String log) {

        StringJoiner stringJoiner = new StringJoiner(" | ");
        // 获取时间戳
        long timestamp = System.currentTimeMillis();
        String threadId = String.format("%-5d", Thread.currentThread().getId());
        String threadName = Thread.currentThread().getName();

        String logInfo = stringJoiner.add(String.valueOf(timestamp))
                .add(threadId)
                .add(threadName)
                .add(log).toString();

        System.out.println(logInfo);
    }

    // 打印当前时间戳
    public static long getTimestamp() {
        return System.currentTimeMillis();

    }


    // 读取resource目录下面的文件,获取其中的文本，将内容返回
    public static String readFileToText(String fileName) {
        String path = CommonUtils.class.getClassLoader().getResource("").getPath();
        String filePath = path + fileName;
        try {
            String result = new String(Files.readAllBytes(Paths.get(filePath)));
            return result;
        } catch (IOException e) {
            return "";
        }
    }

    public static String[] readFileToTextArray(String fileName) {

        // 创建一个返回类
        String[] resultList = new String[0];

        BufferedReader br = null;
        if (fileName == null) {
            return new String[0];
        }

        String path = CommonUtils.class.getClassLoader().getResource("").getPath();
        String filePath = path + fileName;
        try {
            br = new BufferedReader(new FileReader(filePath));
            // 将读取的每一行写入resultList中
            String line;
            while ((line = br.readLine()) != null) {
                // 扩容
                resultList = Arrays.copyOf(resultList, resultList.length + 1);
                resultList[resultList.length - 1] = line;

            }
            br.close();
            return resultList;
        } catch (Exception e) {
            return new String[0];
        }


    }


}
